<template>
  <el-dialog :title="titleText" :visible.sync="showDialog" top="0" :close-on-click-modal="false" width="80%" @close="cancel">
    <el-form v-if="selectedItem !== null" ref="form" :model="formData" class="el-form">
      <el-form-item label="加工作业名称：" class="w100p" :rules="[{ required: true }]">
        <el-input :value="selectedItem.taskName" disabled />
      </el-form-item>
      <el-form-item label="加工产品：" class="w100p" :rules="[{ required: true }]">
        <el-input :value="selectedItem.product.productName" disabled />
      </el-form-item>
      <el-form-item label="作业开始时间：" class="w100p" :rules="[{ required: true }]">
        <el-input :value="selectedItem.startTime | formateTime" disabled />
      </el-form-item>
      <el-form-item v-if="type === 'done'" label="作业结束时间：" class="w100p" :rules="[{ required: true }]">
        <el-input :value="formData.endTime | formateTime" disabled />
      </el-form-item>
      <el-form-item v-if="type === 'abort'" label="作业中止时间：" class="w100p" :rules="[{ required: true }]">
        <el-input :value="formData.suspendEndTime | formateTime" disabled />
      </el-form-item>
      <el-form-item label="实际加工量：" class="w100p" prop="actualVolume" :rules="[{ required: true, message: '请输入实际加工量' }]">
        <div class="input-group">
          <el-input-number :precision="0" v-model="formData.actualVolume" type="number" :min="0" placeholder="请输入实际加工量" clearable />
          <div class="append">{{ selectedItem.product.unitName }}</div>
        </div>
      </el-form-item>
      <el-form-item v-if="type === 'abort'" label="中止原因：" class="w100p" prop="suspendReason" :rules="[{ required: true, message: '请输入中止原因' }]">
        <el-input v-model="formData.suspendReason" type="textarea" placeholder="请输入实际加工量" />
      </el-form-item>
      <el-form-item label="产品报废量：" class="w100p">
        <div class="input-group">
          <el-input-number :precision="0" v-model="formData.scrapNum" type="number" :min="0" placeholder="请输入产品报废量" clearable />
          <div class="append">{{ selectedItem.product.unitName }}</div>
        </div>
      </el-form-item>
      <el-form-item label="实际附属品量：" class="w100p">
        <div class="list">
          <div v-for="(item, index) in actTaskAccessoryList" :key="index" class="list-item">
            <el-select v-model="item.materialNo" placeholder="请选择附属品" @change="changeTaskAccessory($event, index)">
              <el-option v-for="innerItem in selectedItem.taskAccessoryList" :key="innerItem.materialNo" :label="innerItem.materialName" :value="innerItem.materialNo" />
            </el-select>
            <div class="input-group">
              <el-input-number :precision="0" v-model="item.num" type="number" :min="0" placeholder="请输入数量" clearable />
              <div class="append">{{ item.unitName }}</div>
            </div>
            <i class="remove-btn el-icon-remove-outline" @click="removeTaskAccessoryList(index)"></i>
          </div>
          <div class="add-btn">
            <i class="el-icon-circle-plus-outline" @click="addTaskAccessoryList"></i>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="原料剩余：" prop="left">
        <el-radio-group v-model="hasLeft">
          <el-radio :label="0">无剩余</el-radio>
          <el-radio :label="1">有剩余</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="hasLeft === 1" label="剩余原料量：" class="w100p" :rules="[{ required: true }]">
        <div class="list">
          <div v-for="(item, index) in actTaskRawMaterialList" :key="index" class="list-item">
            <el-select v-model="item.materialNo" placeholder="请选择原料" @change="changeRawMaterial($event, index)">
              <el-option v-for="innerItem in selectedItem.taskRawMaterialList" :key="innerItem.materialNo" :label="innerItem.materialName" :value="innerItem.materialNo" />
            </el-select>
            <div class="input-group">
              <el-input-number :precision="0" v-model="item.surplusNum" type="number" :min="0" placeholder="请输入数量" clearable />
              <div class="append">{{ item.unitName }}</div>
            </div>
            <i class="remove-btn el-icon-remove-outline" @click="removeRawMaterial(index)"></i>
          </div>
          <div class="add-btn">
            <i class="el-icon-circle-plus-outline" @click="addRawMaterial"></i>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
      <el-button :loading="saveLoading" type="primary" class="savebtn" @click="save()">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import api from '@/api/processing-management/process-task-manage/index';
import { getToken } from '@/utils/auth';
import moment from 'moment';
export default {
  components: {},
  filters: {
    formateTime: function(value) {
      return moment(value).format('YYYY-MM-DD HH:mm:ss');
    }
  },
  props: {
    value: Boolean,
    selectedItem: {
      type: Object,
      default: null
    },
    type: {
      type: String,
      default: 'done'
    }
  },
  data() {
    return {
      formDataDefault: {
        actualVolume: '',
        scrapNum: '',
        endTime: '',
        suspendEndTime: '',
        suspendReason: ''
      },
      formData: {},
      saveLoading: false,
      showDialog: false,
      actTaskAccessoryList: [],
      actTaskRawMaterialList: [],
      updateKey: 0,
      hasLeft: 0
    };
  },
  computed: {
    titleText() {
      return this.type === 'done' ? '完成作业' : '中止作业';
    }
  },
  watch: {
    value(v) {
      this.showDialog = v;
      if (v) {
        this.init();
      }
    }
  },
  created() {
    this.reset();
  },
  mounted() {},
  methods: {
    reset() {
      this.formData = JSON.parse(JSON.stringify(this.formDataDefault));
      this.hasLeft = 0;
      this.actTaskAccessoryList = [];
      this.actTaskRawMaterialList = [];
    },
    init() {
      const { selectedItem, formData } = this;
      if (selectedItem) {
        for (const key in formData) {
          if (Object.hasOwnProperty.call(formData, key)) {
            formData[key] = selectedItem[key];
          }
        }
        this.formData.endTime = Date.now();
        this.formData.suspendEndTime = Date.now();
        this.$refs['form']?.resetFields();
      }
    },
    save() {
      const { formData, selectedItem, actTaskAccessoryList, actTaskRawMaterialList, type } = this;
      const paylod = { ...selectedItem, ...JSON.parse(JSON.stringify(formData)) };
      this.$refs['form'].validate(async valid => {
        if (valid) {
          this.saveLoading = true;
          paylod.endTime = this.$moment(paylod.endTime).format('YYYY-MM-DD HH:mm:ss');
          paylod.suspendEndTime = this.$moment(paylod.suspendEndTime).format('YYYY-MM-DD HH:mm:ss');
          paylod.taskId = selectedItem.taskId;
          const taskAccessoryList = [];
          const taskRawMaterialList = [];
          for (let i = 0; i < actTaskAccessoryList.length; i++) {
            const element = actTaskAccessoryList[i];
            taskAccessoryList.push({
              ...selectedItem.taskAccessoryList.find(i2 => i2.materialNo === element.materialNo),
              ...element
            });
          }
          for (let i = 0; i < selectedItem.taskRawMaterialList.length; i++) {
            const element = selectedItem.taskRawMaterialList[i];
            taskRawMaterialList.push({
              ...element,
              surplusNum: 0,
              ...actTaskRawMaterialList.find(i2 => i2.materialNo === element.materialNo)
            });
          }
          paylod.taskAccessoryList = taskAccessoryList;
          paylod.taskRawMaterialList = taskRawMaterialList;
          paylod.personNo = getToken('personNo');
          paylod.name = getToken('username');
          const postApi = type === 'done' ? api.completeTask : api.suspendTask;
          postApi(paylod)
            .then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg);
                this.close();
                this.$emit('reflash');
              }
            })
            .finally(_ => {
              this.saveLoading = false;
            });
        }
      });
    },
    close() {
      setTimeout(() => {
        this.reset();
        this.$refs['form'].resetFields();
      }, 250);
      this.$emit('input', false);
    },
    cancel() {
      setTimeout(() => {
        this.reset();
        this.$refs['form'].resetFields();
      }, 250);
      this.$emit('input', false);
    },
    addTaskAccessoryList() {
      this.actTaskAccessoryList.push({
        materialNo: '',
        num: '',
        unitName: ''
      });
    },
    removeTaskAccessoryList(index) {
      this.actTaskAccessoryList.splice(index, 1);
    },
    changeTaskAccessory(v, index) {
      const { selectedItem } = this;
      const findTaskAccess = selectedItem.taskAccessoryList.find(i => i.materialNo === v);
      this.actTaskAccessoryList[index].unitName = findTaskAccess.unitName;
      this.actTaskAccessoryList[index].num = 0;
    },
    addRawMaterial() {
      this.actTaskRawMaterialList.push({
        materialNo: '',
        surplusNum: '',
        unitName: ''
      });
    },
    removeRawMaterial(index) {
      this.actTaskRawMaterialList.splice(index, 1);
    },
    changeRawMaterial(v, index) {
      const { selectedItem } = this;
      const find = selectedItem.taskRawMaterialList.find(i => i.materialNo === v);
      this.actTaskRawMaterialList[index].unitName = find.unitName;
      this.actTaskRawMaterialList[index].surplusNum = 0;
    }
  }
};
</script>

<style lang="scss" scoped>
.input-group {
  display: flex;
  align-items: center;
  width: 100%;
  > * {
    &:first-of-type {
      flex: 1;
      width: auto;
    }
  }
  .append {
    flex: 0 0 80px;
    background-color: #f5f7fa;
    color: #909399;
    position: relative;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 0 20px;
    width: 100%;
    box-sizing: border-box;
    height: 36px;
    border-left: none;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
    text-align: center;
  }
}
::v-deep .el-form-item {
  width: 100%;
}
::v-deep .el-form-item__label {
  min-width: 200px !important;
}
::v-deep .el-form-item__content {
  min-height: 36px;
  align-items: center;
}
.list {
  width: 100%;
  .list-item {
    margin-bottom: 5px;
    display: flex;
    align-items: center;
    > * {
      &:first-child {
        margin-right: 5px;
        flex: 0 0 50%;
      }
      &:last-child {
        margin-left: 5px;
      }
    }
    &:last-of-type {
      margin-bottom: 0;
    }
    .remove-btn {
      cursor: pointer;
      font-size: 18px;
      &:hover {
        color: #f56c6c;
      }
    }
  }
  .add-btn {
    cursor: pointer;
    font-size: 20px;
  }
}
</style>
